<template>
  <div class="tag-manager-box">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-collection-tag"></i> 标签管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="tag-manager-content-box">
      <div class="toolbar-box">
        <el-button class="mr-10" type="primary" icon="el-icon-delete" @click="handleBatchDelete()" :disabled="multipleSelection.length === 0">批量删除</el-button>
        <el-input
            class="mr-10"
            placeholder="标签名"
            v-model="inputTag"
            style="width: 300px;margin-left: 30px;"
            clearable>
        </el-input>
        <el-button class="mr-10" type="primary" icon="el-icon-search" @click="handleSearch()">搜索</el-button>
        <el-button class="btn-add" style="text-align: right" type="primary" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
      </div>
      <div class="content-table-box">
        <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
            border>
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="tag_name"
              label="标签名">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--      分页器      -->
      <div class="pagination-box">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalTag"
            background>
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {createTag, delTag, listTags, modifyTag} from "@/api/apis";

export default {
  name: "TagsManager",
  data(){
    // var validateTagName = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入密码'));
    //   } else {
    //     if (this.ruleForm.password !== '') {
    //       callback();
    //     }
    //     callback();
    //   }
    // };
    return {
      inputTag: '',
      tableData: [],
      totalTag: 0,
      currentPage: 1,
      pageSize: 20,
      multipleSelection: [],
    }
  },
  created(){
    const page = this.$route.query.page
    const size = this.$route.query.size
    if (page){
      this.currentPage = parseInt(page)
    }
    if(size){
      this.pageSize = parseInt(size)
    }
    this.getListTag()
  },
  methods: {
    getListTag(title=null){
      let params = new URLSearchParams()
      params.append('page', this.currentPage)
      params.append('size', this.pageSize)
      if(title){
        params.append('tag_name_contains', this.inputTag)
      }
      listTags(params).then(response =>{
        this.tableData = response.results.data
        this.totalTag = response.count
      }).catch(err => {
        this.$message.error(err.data.message)
      })
    },
    handleCurrentChange(page){
      this.currentPage = page
      this.$router.push({
        name: 'tag-manager',
        query: {
          page: this.currentPage,
          size: this.pageSize,
        }
      })
      this.getListTag()
    },
    handleSizeChange(size){
      this.pageSize = size
      if (size > this.totalTag){
        this.currentPage = 1
      }
      this.$router.push({
        name: 'tag-manager',
        query: {
          page: this.currentPage,
          size: this.pageSize,
        }
      })
      this.getListTag()
    },
    // 多选框回调函数
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleEdit(index, row){
      // let that = this
      this.$prompt('请输入标签名', '修改标签名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.tag_name,
        inputValidator: (value)=> {
          if(row.tag_name === value){
            return '新标签名与旧标签名相同'
          }
        },
        // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: '未修改标签名',
      }).then(({value}) => {
        // this.$message.success(value)
        let params = new URLSearchParams()
        params.append('tag_name', value)
        params.append('id', row.id)
        modifyTag(params).then(response => {
          this.getListTag()
          this.$message({
            type: 'success',
            message: response.message
          });
        }).catch(err => {
          this.$message.error(err.data.message)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
      });
    },
    handleDelete(index, row){
      this.handleBatchDelete(row.id)
    },
    handleBatchDelete(id=null){
      let ids = []
      if (id){
        ids = id
      }else{
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
      }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTag({'ids': ids}).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          });
          this.getListTag()
        }).catch(err => {
          console.log(err)
          this.$message({
            type: 'error',
            message: err.data.message
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSearch(){
      if(this.inputTag !== ''){
        // console.log(this.inputTag)
        this.getListTag(true)
      }else{
        this.getListTag()
      }
    },
    handleAdd(){
      this.$prompt('请输入标签名', '新增标签', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: '邮箱格式不正确'
      }).then(({value}) => {
        let params = new URLSearchParams()
        params.append('tag', value)
        createTag(params).then(response => {
          this.getListTag()
          this.$message({
            type: 'success',
            message: response.message
          });
        }).catch(err => {
          this.$message.error(err.data.message)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消创建'
        });
      });
    },
  },
}
</script>

<style scoped>
  .mr-10{
    margin-right: 10px;
  }
  .tag-manager-content-box{
    margin-top: 10px;
    background-color: white;
    padding: 10px;
    border-radius: 5px;
  }
  /* 解决表头布局错位的bug */
  /*/deep/ .el-table th.gutter{*/
  /*  display: table-cell!important;*/
  /*}*/
  .content-table-box{
    margin-top: 10px;
  }
  .pagination-box{
    margin-top: 20px;
    text-align: right;
  }
  .btn-add{
    float: right;
    margin-right: 10px;
  }
</style>
